package com.szx.kaihei.service.impl;

import cn.hutool.json.JSONUtil;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.szx.kaihei.config.AliyunSmsConfig;
import com.szx.kaihei.exceptions.CustomException;
import com.szx.kaihei.exceptions.ExceptionEnums;
import com.szx.kaihei.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private AliyunSmsConfig aliyunSmsConfig;
    public  void sendSms(String phone, String code){
        try {

            Client client = aliyunSmsConfig.createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName(aliyunSmsConfig.getSignName())
                    .setTemplateCode(aliyunSmsConfig.getTemplateCode())
                    .setTemplateParam("{\"code\":\"" + code + "\"}");
            SendSmsResponse sendSmsResponse = client.sendSms(sendSmsRequest);
            System.out.println("返回信息" + JSONUtil.toJsonStr(sendSmsResponse.getBody()));
            if (sendSmsResponse.getBody().getCode().equals("OK")){
                System.out.println("发送验证码成功");
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new CustomException(ExceptionEnums.USER_CODE_SEND_ERROR);
        }
    }
}
